import { Module } from 'vuex';
import { ILoginState, IAccountInfo } from './type';
import { IRootState } from '../type';
import router from '@/router';
import {
  accountLoginRequest,
  getUsersInfoRequest,
  getUsersMenuRequest
} from '@/service/login/login';
import localCache from '@/utils/localCache';
import { mapMenuToRoute, mapMenusToPermissions } from '@/utils/mapMenus';
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      id: 0,
      token: '',
      name: '',
      userInfo: {},
      userMenus: [],
      userPermission: []
    };
  },
  mutations: {
    changeLoginInfo(state, payload) {
      state.token = payload.token;
      state.name = payload.name;
      state.id = payload.id;
    },
    changeUserInfo(state, payload) {
      state.userInfo = payload;
    },
    changeUserMenu(state, payload) {
      state.userMenus = payload;
      const routes = mapMenuToRoute(payload);
      /* 动态添加路由 */
      routes.forEach((item) => router.addRoute('main', item));
      /* 拿到用户权限并传到state里面 */
      state.userPermission = mapMenusToPermissions(payload);
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccountInfo) {
      /* 请求token */
      const accountResult = await accountLoginRequest(payload);
      const { token, id, name } = accountResult.data;
      commit('changeLoginInfo', accountResult.data);
      localCache.setCache('token', token);
      localCache.setCache('id', id);
      /* 获取用户信息数据 */
      const userInfo = await getUsersInfoRequest(accountResult.data.id);
      commit('changeUserInfo', userInfo.data);
      localCache.setCache('userInfo', userInfo.data);
      /* 根据用户id获取用户权限菜单 */
      const userMenu = await getUsersMenuRequest(userInfo.data.id!);
      commit('changeUserMenu', userMenu.data);
      localCache.setCache('userMenu', userMenu.data);
      /* 跳转到首页 */
      router.push('/main');
    },
    loginStateInit({ commit }) {
      if (localCache.getCache('token')) {
        commit('changeLoginInfo', {
          token: localCache.getCache('token'),
          id: localCache.getCache('id'),
          name: localCache.getCache('name')
        });
      }
      if (localCache.getCache('userInfo')) {
        commit('changeUserInfo', localCache.getCache('userInfo'));
      }
      if (localCache.getCache('userMenu')) {
        commit('changeUserMenu', localCache.getCache('userMenu'));
      }
    }
  }
};
export default loginModule;
